package com.ruoyi.framework.config;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.security.core.Authentication;

import java.util.Objects;
import java.util.Optional;

/**
 * spring data jpa  配置
 *
 * @author xueyu
 */
@Slf4j
@Configuration
@EnableJpaAuditing
public class SpringDataJpaConfig implements AuditorAware<String> {


    /**
     * 审计记录创建或修改用户
     *
     * @return Optional
     */
    @Override
    public Optional<String> getCurrentAuditor() {
        try {
            Authentication authentication = SecurityUtils.getAuthentication();
            if (Objects.isNull(authentication) || !authentication.isAuthenticated()) {
                return Optional.empty();
            }
            String userName;
            Object principal = authentication.getPrincipal();
            if (principal instanceof LoginUser) {
                userName = ((LoginUser) principal).getUsername();
            } else {
                userName = principal.toString();
            }
            return Optional.ofNullable(userName);
        } catch (Exception e) {
            log.error("error", e);
            return Optional.empty();
        }
    }
}
